const { Server } = require('socket.io')

const io = new Server({
  cors: {
    origin: '*'
  },
  // base64 限制 默认为 1M 1e6
  maxHttpBufferSize: 1e7
})

// 记录连接对象
const clientList = []

io.on('connection', (socket) => {

  clientList.push(socket)

  socket.on('disconnect', (socket) => {
    clientList.splice(clientList.indexOf(socket), 1)
  })

  socket.on('enter', userData => {
    io.emit('msg', { msg: `欢迎 ${userData.userName} 进入聊天室！` })
  })

  socket.on('leave', user => {
    io.emit('msg', { msg: `用户 ${user.userName} 离开聊天室！` })
  })

  socket.on('sendMsg', data => {
    io.sockets.emit('newMsg', data)
  })

  // socket.on('disconnect', (reason) => {
  //   console.log('断开连接', reason)
  // })
})

module.exports = io
